﻿using UnityEngine;
using System.Collections;
using Dict.DataModel;

namespace Room
{
    public class RCAIUnionTransfer : RCAIUnionFightBase
    {
        TableUnionFightTransfer dictData;

        Vector2 pos;
        float minDisance;
        Vector3 target;
        float cooldtime = 0f;

        GameObject tranferObj;

        public RCAIUnionTransfer(RoomCharactor owner)
            :base(owner)
        {
            this.type = AIType.UnionTransfer;
        }

        public void Init(TableUnionFightTransfer transfer)
        {
            dictData = transfer;
            var temp = Dict.Blo.DictUnionFightTransferBlo.GetPosition(transfer.UFTransferId);
            pos = new Vector2(temp.x, temp.z);
            target = CommonMethod.GetPosition(dictData.TransferEnd);
            cooldtime = 0f;
            SetCamp(dictData.Camp);

            minDisance = (float)dictData.StartR;

            tranferObj = Spawn(RoomUnionFight.TRANSFER_STATIC);
        }

        public override void Tick()
        {
            base.Tick();

            cooldtime -= Time.deltaTime;
            if (cooldtime <= 0f)
            {
                CheckNearCharactor();
            }
        }

        void CheckNearCharactor()
        {
            var myself = owner.charactorManager.GetSelfCharactor();
            if(myself!=null)
            {
                var ai = myself.ai as RCAIUnionActor;
                if (ai.IdleState() && ai.Camp == Camp)
                {
                    var pos0 = new Vector2(myself.transform.position.x, myself.transform.position.z);
                    var dis = Vector2.Distance(pos0, pos);
                    if (dis < minDisance)
                    {
                        cooldtime = 1f;
                        SendMyselfTransfer();
                    }
                }
            }
        }

        void SendMyselfTransfer()
        {
            var net = NetUnionFightBase.GetNet();
            if(net!=null)
            {
                net.SendCSBeginTransfer(target, dictData.UFTransferId);
            }
        }

        public override void DoStop()
        {
            base.DoStop();
            if (tranferObj != null)
                Unspawn(tranferObj);
        }
    }
}
